package com.oocl.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

import com.oocl.annotation.Transactional;
import com.oocl.util.DBUtil;

public class ServiceProxy implements InvocationHandler {
	Object target;
	
	public ServiceProxy(Object target) {
		this.target = target;
	}
	
	public Object createProxy(){
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if(!method.isAnnotationPresent(Transactional.class)){	// 不开启事务
			Object obj=null;
			Connection connection =null;
			try {
				connection= DBUtil.getConnection();
				obj = method.invoke(target, args);
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				DBUtil.remove(connection);
			}
			return obj;
		}
		//开启事务
		Connection connection = null;
		Object returnValue = null;
		try {
			connection = DBUtil.getConnection();
			System.out.println("开启事务");
			connection.setAutoCommit(false);
			returnValue = method.invoke(target, args);
			connection.commit();
			System.out.println("提交事务");
		} catch (Exception e) {
			connection.rollback();
			e.printStackTrace();
		}finally {
			DBUtil.remove(connection);
		}
		return returnValue;
	}

}
